<template>
  <div class="app-container">
    <el-row style="margin-bottom:10px">
      <el-button v-if="!businessInfo.parentId"  type="primary" size="small" @click="$router.push('/mechanism/school/add')">新增分校</el-button>
    </el-row>
    <el-table
      :data="data"
      border
      fit
      style="width: 100%"
      max-height="730"
      :element-loading-text="global.loadingStr"
      :header-cell-style="{background:global.mainColor}"
    >
      <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
      <el-table-column label="机构logo" align="center" width="160">
        <template slot-scope="{row}">
          <img style="width:100px" :src="row.logoImg">
        </template>
      </el-table-column>
      <el-table-column label="机构名称" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="businessDiscountAmount" label="详细地址" align="center">
        <template slot-scope="{row}">
          <span>{{ row.city }}{{ row.detail }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开业日期" align="center">
        <template slot-scope="{row}">
          <span class="text_color">{{ row.foundTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="commission" label="校长（负责人）" align="center">
        <template slot-scope="{row}">
          <span class="text_color">{{ row.principalName }}</span>
          <el-button type="text" @click="replaceCommission(row)">( 更换 )</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="paidInAmount" label="服务电话" align="center">
        <template slot-scope="{row}">
          <span class="text_color">{{ row.serverPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="actualCollection" label="状态" align="center">
        <template slot-scope="{row}">
          <span class="text_color">{{ row.status | status}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="actualCollection" label="操作" align="center" width="300">
        <template slot-scope="{row,$index}">
          <el-button size="small" type="primary" @click="handleEdit(row,$index)">编辑</el-button>
          <el-button v-if="row.status===2" size="small" type="danger" @click="handleDisable(row)">禁用</el-button>
          <el-button v-if="row.status===3" size="mini" type="success" @click="handleEnable(row)">启用</el-button>
          <el-button v-if="row.status===2" size="small" type="primary" @click="handleQrCode(row)">机构推广码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row type="flex" justify="center" style="margin-top:10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-row>
    <!-- 更换校长 -->
    <el-dialog
      :visible.sync="principalName.dialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="$refs.principalNameForm.resetFields()"
      width="800px"
    >
      <h3 slot="title">{{principalName.title}}</h3>
      <div style="margin-bottom:10px">提示：更换分校校长，需要把目前的分校校长先禁用，才能进行新增校长或者启用之前的分校校长</div>
      <el-form
        ref="principalNameForm"
        :model="principalName.form"
        :rules="principalName.rules"
        label-width="80px"
      >
        <el-form-item label="校长（负责人）" label-width="120px" prop="name">
          <el-row type="flex" justify="space-between">
            <el-col :span="6">
              <el-input v-model="principalName.form.name" placeholder="请输入校长（负责人）名字"></el-input>
            </el-col>
            <el-col :span="12">
              <span>登录账号： {{principalName.form.phone}}</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="负责人电话" label-width="120px" prop="phone">
          <el-row type="flex" justify="space-between">
            <el-col :span="6">
              <el-input v-model="principalName.form.phone" placeholder="请输入负责人电话"></el-input>
            </el-col>
            <el-col :span="12">
              <span>初始密码： JBL123456</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label-width="120px">
          <el-button
            style="width:120px"
            type="primary"
            size="small"
            @click="handleAddPrincipal('principalNameForm')"
          >添加</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="principalName.data"
        border
        fit
        height="300"
        style="width: 100%;"
        :element-loading-text="global.loadingStr"
        :header-cell-style="{background:global.mainColor}"
      >
        <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
        <el-table-column label="校长（负责人）" align="center" width="160">
          <template slot-scope="{row}">
            <span>{{ row.nickName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="160">
          <template slot-scope="{row}">
            <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="登录账号" align="center" />
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="{row}">
            <el-button v-if="row.status===1" size="mini" type="danger" @click="disablePrincipal(row)">禁用</el-button>
            <el-button v-if="row.status===0" size="mini" type="success" @click="updatePrincipal(row)">启用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
      <!-- 课程推广码 -->
    <el-dialog
      :title="qrCodeName"
      :visible.sync="qrDialog"
      width="600px"
    >
      <el-row type="flex" justify="center">
        <el-image class="qrcode-img" :src="qrCodeUrl" />
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="qrDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import md5 from 'js-md5'
import {
  selectByConditions,
  dismountGrounding,
  selectPrincipalListByOrgId,
  updatePrincipalStatus,
  addPrincipal,
  QRcode
} from '@/api/mechanism'

export default {
  name: 'Framework',
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!(/^1[3456789]\d{9}$/.test(value))) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    return {
      currentRow: {},
      qrDialog: false,
      qrCodeName: '',
      qrCodeUrl: '',
      data: [],
      page: 1,
      pageSize: 10,
      total: 0,
      principalName: {
        dialog: false,
        title: '',
        data: [],
        form: {
          name: '',
          phone: ''
        },
        rules: {
          name: [
            {
              required: true,
              message: '请输入校长（负责人）姓名',
              trigger: 'blur'
            }
          ],
          phone: [
            { required: true, message: '请输入负责人电话', trigger: 'blur' },
            { validator: validatePhone, trigger: 'change' }
          ]
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'businessInfo'
    ])
  },
  filters: {
    status(v) {
      switch (v) {
        case 1:
          v = '待审核'
          break

        case 2:
          v = '启用'
          break

        case 3:
          v = '禁用'
          break
      }
      return v
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleEdit(row,$index) {
      let title = $index === 0 ? '总校':'分校'
      this.$router.push({
        path: '/mechanism/school/edit',
        query: {
          id: row.id,
          title:title
        }
      })
    },
    // 禁用分校
    handleDisable(row) {
      dismountGrounding({
        status: 3,
        businessId: row.id
      }).then(res => {
        this.$message({
          message: '禁用成功',
          type: 'success'
        })
        this.getList()
      })
    },
    // 启用分校
    handleEnable(row) {
      dismountGrounding({
        status: 2,
        businessId: row.id
      }).then(res => {
        this.$message({
          message: '禁用成功',
          type: 'success'
        })
        this.getList()
      })
    },
    async handleQrCode(row) {
      const res = await QRcode({
        id: row.id,
        pagesPath: `pages/mechDetail/mechDetail`
      })
      const data = res.data
      if (!data) return
      if (data instanceof Object) {
        this.qrCodeUrl = data.qrcodeImg
      } else {
        this.qrCodeUrl = data
      }
      this.qrCodeName = row.name
      this.qrDialog = true
    },
    replaceCommission(row) {
      this.currentRow = row
      this.principalName.dialog = true
      this.principalName.title = `${row.name} 更换校长`
      this.getPrincipalList()
    },
    getPrincipalList() {
      selectPrincipalListByOrgId({
        businessId: this.currentRow.id
      }).then(res => {
        this.principalName.data = res.data
      })
    },
    handleAddPrincipal(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addPrincipal({
            businessId: this.currentRow.id,
            realName: this.principalName.form.name,
            phone: this.principalName.form.phone,
            password: md5('JBL123456'),
            nickName: this.principalName.form.name,
            orgId: this.currentRow.id,
            identity: 3,
            status: '1'
          }).then(res => {
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.getPrincipalList()
          })
        } else {
          return false
        }
      })
    },
    disablePrincipal(row) {
      updatePrincipalStatus({
        businessId: this.currentRow.id,
        id: row.id,
        status: '0'
      }).then(res => {
        this.$message({
          message: '禁用成功',
          type: 'success'
        })
        this.getPrincipalList()
      })
    },
    updatePrincipal(row) {
      updatePrincipalStatus({
        businessId: this.currentRow.id,
        id: row.id,
        status: '1'
      }).then(res => {
        this.$message({
          message: '启用成功',
          type: 'success'
        })
        this.getPrincipalList()
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getList()
    },
    getList() {
      selectByConditions({
        parentId: this.$store.getters.businessId,
        currentPage: this.page,
        pageSize: this.pageSize,
        name: this.$store.getters.name
      }).then(res => {
        this.page = res.data.current
        this.total = res.data.total
        this.data = res.data.records
      })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
